package cn.com.miao.lynx.service.system.service.impl;

import cn.com.miao.lynx.common.base.repository.BaseRepository;
import cn.com.miao.lynx.service.system.entity.SysPermission;
import cn.com.miao.lynx.service.system.entity.SysRole;
import cn.com.miao.lynx.service.system.entity.SysUser;
import cn.com.miao.lynx.service.system.repository.SysRoleRepository;
import cn.com.miao.lynx.service.system.repository.SysUserRepository;
import cn.com.miao.lynx.service.system.service.SysPermissionService;
import cn.com.miao.lynx.service.system.service.SysUserService;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * SysUserServiceImpl
 *
 * @title: SysUserServiceImpl
 * @description:
 * @author: dengmiao
 * @create: 2019-12-24 11:22
 **/
@Slf4j
@Data
@AllArgsConstructor
@Service
public class SysUserServiceImpl implements SysUserService {

    private final SysUserRepository sysUserRepository;

    private final SysRoleRepository sysRoleRepository;

    private final SysPermissionService sysPermissionService;

    @Override
    public BaseRepository<SysUser, Long> getRepository() {
        return this.getSysUserRepository();
    }

    @Override
    public SysUser findUserByUsername(String username) {
        SysUser sysUser = sysUserRepository.findSysUserByUsername(username);
        return completedSysUser(sysUser);
    }

    @Override
    public SysUser findUserByPhone(String phone) {
        SysUser sysUser = sysUserRepository.findSysUserByPhone(phone);
        return completedSysUser(sysUser);
    }

    private SysUser completedSysUser(SysUser sysUser) {
        if (sysUser != null) {
            Long userId = sysUser.getId();
            // 角色 本地sql查询
            Set<SysRole> roles = sysRoleRepository.findAllByUserId(userId);
            sysUser.setRoles(roles);
            // 权限 query dsl查询
            List<SysPermission> permissions = sysPermissionService.findPermissionListByUserId(userId);
            sysUser.setPermissions(permissions);
        }
        return sysUser;
    }
}
